var redisClient = require('../config/redis_database').redisClient;
var db = require('../config/mongo_database');
var moment = require('moment');
var request = require('request');
var tokenManager = require('../config/token_manager');
var md5 = require('md5');
var TIME_OUT = 60 * 5;
let SMS_URL = 'https://sms.yunpian.com/v2/sms/single_send.json';

// 动态校验码
exports.reSend = function (req, res, next) {
	let question = {
		"0" : {"id":"1"  ,"que":"1 + 2 = ?", "ok":"3"},
		"1" : {"id":"1"  ,"que":"1 + 1 = ?", "ok":"2"},
		"2" : {"id":"2"  ,"que":"2 + 4 = ?", "ok":"6"},
		"3" : {"id":"3"  ,"que":"3 * 3 = ?", "ok":"9"},
		"4" : {"id":"4"  ,"que":"10 + 10 = ?", "ok":"20"},
		"5" : {"id":"5"  ,"que":"4 * 4 = ?", "ok":"16"},
		"6" : {"id":"6"  ,"que":"18 - 10 = ?", "ok":"8"},
		"7" : {"id":"7"  ,"que":"4 - 2 = ?", "ok":"2"},
		"8" : {"id":"8"  ,"que":"5 * 1 = ?", "ok":"5"},
		"9" : {"id":"9"  ,"que":"9 - 6 = ?", "ok":"3"},
		"9" : {"id":"10"  ,"que":"9 - 5 = ?", "ok":"4"}
	};
	var index = Math.round(Math.random()*9);
	var resque = question[index];
	resque["id"]= moment(new Date()).format("YYYYMMDDHHmmss");
	redisClient.set(resque["id"], resque["ok"]);
    redisClient.expire(resque["id"], TIME_OUT); // 5分钟失败

    resque.ok = undefined; // 清空答案
    res.json(resque);
};

// 发送短信
exports.sendsms = function(req, res){
	var username = req.body.username || '';
	var vcode = req.body.vcode || '';
	var vid = req.body.vid || '';
	if(username == ''){
		res.sendStatus(403); //手机号为空
	}
	if(vcode == '' || vid == ''){
		res.sendStatus(402); //动态验证码为空
	}
	var remoteip = req.connection.remoteAddress;
	console.log(remoteip)
	redisClient.get(remoteip, function (err, ip) {
		if(ip){
            res.json({status:501, msg:"发送短信时间请求过于频繁" });
        } else {
            redisClient.get(vid, function (err, code) {
				if (err || vcode!=code)
				    res.sendStatus(500); // 验证码错误
				if (vcode==code) { // 验证成功发送验证码
					var smsJson = {
						apikey:"966f88af7f6c20b51bb758ffa50c197c",
						text:"【布谷鸟源码网】您的验证码是000000， 本次验证码10分钟内有效。",
						mobile:""
					};
					
					var SMS_CODE = moment(new Date()).format("mmssSS"); //验证码
					smsJson.mobile = username;
					smsJson.text = smsJson.text.replace("000000", SMS_CODE); // 验证码替换模板
					console.log(smsJson);

					request.post({url:SMS_URL, form: smsJson}, function(err,httpResponse,body){
						var object = JSON.parse(body);
						if(object["code"]==0){
							redisClient.set(username, SMS_CODE);
		    				redisClient.expire(username, TIME_OUT*2); // 10分钟失败
		    				redisClient.del(vid);
		    				redisClient.set(remoteip, 1);
							redisClient.expire(remoteip, 50); //同一个IP50秒生效一次
		    				res.sendStatus(200);
						}else{
							res.json({status:501, msg:object["msg"] });
						}
					});
				
				}
			});
        }
	});

	
};

// 发送忘记短信
exports.sendpwdsms = function(mobile, content){
	var smsJson = {
		apikey:"966f88af7f6c20b51bb758ffa50c197c",
		text: content,
		mobile: mobile
	};
	
	console.log(smsJson);

	request.post({url:SMS_URL, form: smsJson}, function(err,httpResponse,body){
		console.log(body)
		var object = JSON.parse(body);
		if(object["code"]==0){
			console.log("redissms", username, SMS_CODE)
			redisClient.set(username, SMS_CODE);
			redisClient.expire(username, TIME_OUT*2); // 10分钟失败
			redisClient.del(vid);
			res.sendStatus(200);
		}else{
			 res.json({status:501, msg:object["msg"] });
		}
	});
			
	
};
